<?php

class OrderBulider_Module{

    const TYPE_WAIMAI  = 'WAIMAI';
    const TYPE_DINGCAN = 'DINGCAN';

    private $orderSn   = '';
    private $orderPwd  = '';
    private $userId    = 0;
    private $shopId    = 0;
    private $orderType = '';
    private $mobile    = '';
    private $telphone  = '';
    private $address   = '';
    private $realname  = '';
    private $memo      = '';

    private $shopInfo  = array();
    private $dishes    = array();
    private $sumPrice  = 0;

    function __construct($order_type){
        $this->setOrderType($order_type);
    }

    /**
     * 初始化信息
    **/
    public function initData(array $post){
        $realname = array_get_string($post, 'realname');
        $gender = array_get_string($post, 'gender');
        if($gender){
            $realname .= $gender == 'F' ? ' 女士' : ' 先生';
        }
        $this->setRealname($realname);

        if($this->orderType == self::TYPE_DINGCAN){
            $memo = '预计就餐时间:' .array_get_string($post, 'orderdate').' '.array_get_string($post, 'ordertime'). ';'
                  . '预计就餐人数:' .array_get_string($post, 'person', '未订'). ';'
                  . '其他信息:' .array_get_string($post, 'memo', '无');
        }else{
            $memo = array_get_string($post, 'memo');
        }

        $this->setUserId(array_get_int($post, 'user_id'));
        $this->setShop(array_get_int($post, 'shop_id'));
        $this->setDish(array_get($post, 'itemNum'));
        $this->setMobile(array_get_string($post, 'mobile'));
        $this->setTelphone(array_get_string($post, 'telphone'));
        $this->setAddress(array_get_string($post, 'address'));
        $this->setMemo($memo);
    }

    public function setOrderType($order_type){
        $this->orderType = strtolower($order_type) == 'waimai' ? self::TYPE_WAIMAI : self::TYPE_DINGCAN;
    }

    public function getOrderType(){
        return $this->orderType;
    }

    public function setUserId($user_id){
        $this->userId = intval($user_id);
    }

    public function getUserId(){
        return $this->userId;
    }

    public function setShop($shop_id){
        $this->shopId = intval($shop_id);
        if($this->shopId){
            $this->shopInfo = $this->getShop($this->shopId);
        }
        if(!$this->shopInfo){
            $this->shopId = 0;
        }
    }

    public function getShopInfo(){
        return $this->shopInfo;
    }

    public function getShopId(){
        return $this->shopId;
    }

    public function setDish(array $dish_num){
        if($this->shopId){
            $this->dishes   = $this->getDishesWithNum($dish_num);
            $this->sumPrice = $this->totalPrice();
        }
    }

    public function getDishes(){
        return $this->dishes;
    }

    public function getSumPrice(){
        return $this->sumPrice;
    }

    public function setRealname($realname){
        $this->realname = $realname;
    }

    public function getRealname(){
        return $this->realname;
    }

    public function setMobile($mobile){
        $this->mobile = $mobile;
    }

    public function getMobile(){
        return $this->mobile;
    }

    public function setTelphone($telphone){
        $this->telphone = $telphone;
    }

    public function getTelphone(){
        return $this->telphone;
    }

    public function setAddress($address){
        $this->address = $address;
    }

    public function getAddress(){
        return $this->address;
    }

    public function setMemo($memo){
        $this->memo = $memo;
    }

    public function getMemo(){
        return $this->memo;
    }

    private function genOrderSn(){
        if($this->orderType == self::TYPE_WAIMAI){
            return sprintf('W%010d_%05d_%03d', date('mdHis'), $this->shopId, $this->getTotalOrder($this->shopId) + 1);
        }elseif($this->orderType == self::TYPE_DINGCAN){
            return strtoupper(App::getCityPerfix()).date('mdHis').rand(1000, 9999);
        }else{
            return randstr(12);
        }
    }

    public function getOrderSn(){
        return $this->orderSn;
    }

    private function genOrderPwd(){ //8位密码
        return rand(10000000, 99999999);
    }

    public function getOrderPwd(){
        return $this->orderPwd;
    }

    public function getOrderTitle(){
        return sprintf('%s%d元预订券', $this->shopInfo['name'], $this->sumPrice);
    }

    public function getOrderDesc($full = false){
        $ret = $this->shopInfo['name'];
        $ret .= "\r\n".'订单号:'.$this->orderSn.',';
        if($full)
            $ret .= "\r\n".'密码:'.$this->orderPwd.'.';
        $ret .= "\r\n".'预订菜单:';
        foreach($this->dishes as $dish){
            $ret .= "\r\n  ".$dish['name'].'('.$dish['price'].'元x'.$dish['number'].'份);';
        }
        $ret .= "\r\n".'总计:'.$this->sumPrice.'元';
        return $ret;
    }

    public function genMessage($msg){
        if(preg_match_all('/\{(\w+)\}/i', $msg, $m)){
            foreach($m[1] as $method){
                if(method_exists($this, "get{$method}")){
                    $text = call_user_func(array($this, "get{$method}"));
                    $msg = str_replace('{'.$method.'}', $text, $msg);
                }
            }
        }
        return $msg;
    }

    /**
     * 校验店铺设置
     *
     * @return false|string  错误信息，若为 false 则无错误
    **/
    public function checkShop(){
        $error = false;
        if(!$this->shopId || !$this->shopInfo){
            $error = '店铺不存在，无法生产订单';
        }elseif(!$this->dishes){
            $error = '购物车为空，请重新添加菜品';
        }elseif(!($this->shopInfo['status'] >= 2 && Util::isMobile($this->shopInfo['sms_number']))){
            $error = '店铺设置错误，无法进行订餐服务';
        }
        return $error;
    }

    /**
     * 创建订单
     *
     * @param array 菜品 ID/数量 数组
     * @return array
    **/
    public function createOrder(){
        //订单号及密码
        $this->orderSn  = $this->genOrderSn();
        $this->orderPwd = $this->genOrderPwd();

        $data = array(
            'order_code'  => $this->orderSn,
            //'order_pwd'   => $this->orderPwd,
            'order_type'  => $this->orderType,
            'user_id'     => $this->userId,
            'shop_id'     => $this->shopId,
            'realname'    => $this->realname,
            'mobile'      => $this->mobile,
            'telphone'    => $this->telphone,
            'address'     => $this->address,
            'memo'        => $this->memo,
            'price'       => $this->totalPrice(),
            'create_dt'   => date('Y-m-d H:i:s'),
            'status'      => 0,
         );
        $order_id =  Db::insert('biz_order', $data);

        if($order_id){
            //创建 order_item
            $price = 0;
            $stmt = Db::prepare("INSERT INTO `biz_order_item` (order_id, dish_id, number, name, price) VALUES (?,?,?,?,?)");
            $stmt->bind_param('iiisd', $order_id, $dish_id, $number, $name, $price);
            foreach($this->dishes as $dish_id => $dish){
                $number = $dish['number'];
                $price  = $dish['price'];
                $name   = $dish['name'];
                $stmt->execute();
            }
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取餐厅的当天订单数量
     *
     * @param int 店铺Id
     * @return int
    **/
    private function getTotalOrder($shop_id){
        return Db::getFirst("SELECT COUNT(order_id) FROM `biz_order` WHERE shop_id = '{$this->shopId}' AND create_dt LIKE '" .date('Y-m-d'). "%'");
    }

    /**
     * 获取餐厅信息
     *
     * @param int 店铺Id
     * @return array
    **/
    private function getShop($shop_id){
        return Db::getRow("SELECT * FROM `biz_shop` WHERE shop_id = '$shop_id'");
    }

    /**
     * 获取菜品信息
     *
     * @param array 菜品 ID/数量 数组
     * @return array
    **/
    private function getDishesWithNum(array $dishIdNum){
        $dishIds = array_keys($dishIdNum);
        $data = Db::getKeyArray("SELECT dish_id, name, price, money, 0 as `number` FROM `biz_dish` WHERE
                                 shop_id = '{$this->shopId}' AND dish_id IN ('".join("', '", $dishIds)."')", 'dish_id');
        foreach($data as $dish_id => $item){
            $data[$dish_id]['number'] = intval($dishIdNum[$dish_id]);
        }
        return $data;
    }

    //计算价格(售价)
    private function totalPrice(){
        $price = 0;
        foreach($this->dishes as $item){
            $price += $item['number'] * $item['price'];
        }
        return $price;
    }
}
?>